package com.qing.thread.unsafe;

/**
 * 模拟银行取款
 */
public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account(1000, "金主");

        DrawMoney lx = new DrawMoney(account, 50, "lx");
        DrawMoney hwq = new DrawMoney(account, 100, "hwq");
        lx.start();
        hwq.start();
    }
}

//账户
class Account {
    //余额
    int balancesMoney;
    //账户名称
    String name;

    public Account(int balancesMoney, String name) {
        this.balancesMoney = balancesMoney;
        this.name = name;
    }
}

//银行取钱
class DrawMoney extends Thread {
    Account account;
    //取了多少钱
    int drawMoney;
    //手里有多少钱
    int nowMoney;

    public DrawMoney(Account account, int drawMoney, String threadName) {
        super(threadName);
        this.account = account;
        this.drawMoney = drawMoney;
    }

    @Override
    public void run() {
        //同步监视器，锁定要修改的对象
        //锁的对象是变化的量，需要增删改的对象
        //第一个线程进来，锁定同步监视器，执行其中代码
        //第二个线程访问，发现被锁定，无法访问，只能等待
        //第一个线程执行完，解锁同步监视器
        //第二个线程发现没有锁，然后自己再锁定并访问
        synchronized (account) {
            //如果账户余额-要取的钱<0 则代表钱不够
            if (account.balancesMoney - drawMoney < 0) {
                System.out.println("钱不够了");
                return;
            }
            //sleep可以放大问题的发生性，让两个人同时在这等待，一起进行取钱操作，就会发生数据紊乱
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            //账户内余额
            account.balancesMoney = account.balancesMoney - drawMoney;
            //现在手里的钱
            nowMoney = nowMoney + drawMoney;

            System.out.println(this.getName() + "取了" + drawMoney + "ta现在手里有" + nowMoney + "银行账户还有" + account.balancesMoney);

        }

    }
}